package grouper;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

import org.opencv.core.CvType;
import org.opencv.core.Mat;

public class Util {

	public static Mat convert( BufferedImage in ) {
		//System.out.println("Image type: " + in.getType());
		int height 	= in.getHeight();
        int width 	= in.getWidth();
        byte[] data	= ((DataBufferByte) in.getRaster().getDataBuffer()).getData();
        Mat out = null;
        
		if (in.getType() == BufferedImage.TYPE_INT_RGB || in.getType() == BufferedImage.TYPE_INT_ARGB) {
	        out = new Mat(height, width, CvType.CV_8UC3);
		}
		else if (in.getType() == BufferedImage.TYPE_BYTE_GRAY) {
			out = new Mat(height, width, CvType.CV_8UC1);
		}
		
		if (out != null)
			out.put(0, 0, data);
		
		return out;
	}
	
	public static BufferedImage convert( Mat in ) {
		int width 	= in.cols();
		int height 	= in.rows();
		byte[] data	= new byte[width * height * (int)(in.elemSize())];
		int r, g, b;
		BufferedImage image = null;
		
		in.get(0, 0, data);
		if (in.channels() == 3) {
			int[] idata	= new int[width * height * (int)(in.elemSize())];
			
			for (int i = 0; i < data.length; i += 3) {
				r = data[i];
				g = data[i + 1];
				b = data[i + 2];
				idata[i/3] = r + (g << 8) + (b << 16);
			}
			
			image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
			image.getRaster().setDataElements(0, 0, width, height, idata);
		}
		
		if (in.channels() == 1) {
			image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
			image.getRaster().setDataElements(0, 0, width, height, data);
		}
		
		return image;
	}

}
